var ShareURLDialog = (function(){    
    /**
     * 构造函数.
     */
    var _linkManageDialog = function(cfg){
        var _this = this;
        this.setProps({            
            size : {
                width : 765,
                height : 555
            }, 
            buttons : [
                {
                    props : 'save|' + lan('dialog.buttons.save'),
                    handler : function($btnObj) {
                        var formValues = ujs.browser.form.getValues(this.getForm()),
                            ueid = formValues['id'];
                        if(!ujs.browser.form.validate(this.getForm())){
                            return false;
                        }                        
                        _this.showMask('Submitting ...');                        
                        page.biz.uploadURLEntity(ueid || 'new', _this.getFormData(), function(data){ 
                            if(ueid){
                                bubble.msg(lan('app.im.link.updateDone'));    
                            } else {
                                bubble.msg(lan('app.im.link.createDone'));
                            }
                            _this.remove();
                        }, null, function(){
                            _this.hideMask();
                        });
                    }
                }
            ]
        });
        this.addLinkForm();
    }.extend(ujs.ui.Dialog);
    
    /**
     * 初始化表单. 
     */
    _linkManageDialog.prototype.addLinkForm = function(){
        var _this = this;
        this.addDialogContent(URLDialogView.linkForm, function($dialogContent) {
            
            $('.urlInput2').blur(function(){
                var urlBox = $(this);
                var url = $(this).val().trim();
                if(url){
                    urlBox.css('background', 'url(/ujs/images/common16/loading.gif) no-repeat right center');
                    _this.getImgPtr = $.ajax({
                        timeout : 10 * 1000,
                        url : '/apis/url/website/info?u={0}'.format(window.encodeURIComponent(url.toLegalURL())),
                        success : function(msg){
                            if(msg['img']){
                                var imgObj = new Image();
                                imgObj.onload = function(){
                                    _this.iconObj.setValue(msg['img']);                                    
                                    urlBox.css('background','none');  
                                } 
                                imgObj.onerror = function(){
                                    urlBox.css('background','none');    
                                }
                                imgObj.src = msg['img'];
                            } else {
                                urlBox.css('background','none');
                            }
                        },
                        error : function(msg){
                            urlBox.css('background','none');                            
                        }
                    }).always(function(){

                    });
                }
            });
            
            
            
            $dialogContent.find('.noshare').remove();
            _this.$selectUserTip = $dialogContent.find('.su');
            //member selector
            _this.memberSelector = new MemberSelector($dialogContent.find('.memberSelector2'), {
                size : {
                    width : 554,
                    height : 90
                },
                treeType : 'web',
                mode : 'expand',
                exclusion : [ujs.util.session.getCurrentUserID()],
                events : {
                    'change' : function(){
                        _this.toggleAdvancedProps();
                    }
                }
            });            
                             
            _this.iconObj = $dialogContent.find('#icon').singleImgUploader({
                style : 'innerIcon',
                width : 60,
                height : 60, 
                toolbar : false,
                value : '/ujs/app/im/images/link.png',
                uploadImmediately : false                
            }).data('singleImgUploader');
            
            _this.iconObj.on('beforeSelectImg', function(){
                if(_this.getImgPtr){
                    _this.getImgPtr.abort();
                }
            })
            
            if(_this.config['mode'] === 'edit'){
                _this.initFormData(_this.config['ueid']);                
            }
            
            if(_this.config['relType'] !== 'web'){
                $dialogContent.find('.urlOnly').remove();
                $dialogContent.find('.surveySelector').css('background','#fff').show();
                $dialogContent.find('.surveySelectorLabel').text('Page Designer');
            }        
        });
    };
   
    //------------------------------------------------------------------------------------------------
    
    /**
     * 初始化表单数据.
     */
    _linkManageDialog.prototype.initFormData = function(urlID){
        var _this = this;
        $.ajax({
            url : '/apis/url/{topicEntityId}'.format({
                topicEntityId : urlID
            }),
            success : ujs.hr(function(msg){                        
                var urlEntity = msg['ue'],
                    isCustomPage = urlEntity.url.indexOf('resource://') === 0,
                    customPageID = urlEntity.url.replace('resource://', '');
                    
                _this.currentEntityID = urlEntity['id'];                
                _this.customPageID = customPageID;                
                ujs.browser.form.setValues(_this.getForm(), urlEntity);                    
                _this.memberSelector.addMembers(urlEntity['participants']).setAdmins(urlEntity['adminUserIds']);                               
                                
            })
        });
    };
      
    /**
     * 获取表单数据. 
     */
    _linkManageDialog.prototype.getFormData = function(){  
        //url基础数据.  
        var formValues = ujs.browser.form.getValues(this.getForm()),
            members = this.memberSelector.getUserAndGroup();
            
        var icon = this.iconObj.getValue();
        if(icon == '/ujs/app/im/images/link.png'){
            icon = '';
        }
            
        var json = {
                url : JSON.stringify({
                    type : this.config['relType'],
                    title : formValues['title'] || formValues['url'],
                    ugids : members['groups'],
                    uids : members['users'].concat(ujs.util.session.getCurrentUserID()), 
                    auids : this.memberSelector.getAdmins().concat(ujs.util.session.getCurrentUserID()),                
                    url : formValues['url'],
                    icon : icon   
                })
            };
        //url图标上传.
        var formData = Object.toFormData(json);        
        this.iconObj.fillupImageFiles(formData, [[200,200]]);        
        return formData;
    };    
    
    //------------------------------------------------------------------------------------------------
    
    _linkManageDialog.prototype.toggleAdvancedProps = function(){   
        var users = this.memberSelector.getUserAndGroup()['users'];
        if(users.length){            
            this.$selectUserTip.show();
        } else {
            this.$selectUserTip.hide();            
        }
    };
    
    
    return _linkManageDialog;    
})();
